<template>
	<view class="container">
		<view class="solid-bottom text-13 flex justify-between align-center padding bg-white">
			<view class="text-333 text-bold"> 取货地址 </view>
			<view class="flex justify-start align-center" @click="changeAddress(1)">
				<!-- 	<view class="text-767696 margin-right-xs">
					{{}}
				</view> -->
				<input type="text" v-model="address" @input="getAddress" disabled
					class="text-767696 margin-right-xs text-right" />
				<image :src="baseUrl + '/static/right.png'" mode="" style="width: 22rpx; height: 22rpx"></image>
			</view>
		</view>
		<view class="margin-bottom-sm bg-white text-13 flex justify-between align-center padding">
			<view class="text-333 flex-sub text-bold"> 详细地址 </view>
			<input type="text" value="" v-model="detailedAddress" class="text-13 flex-treble"
				placeholder="详细地址，例1号楼1层1001室" />
		</view>
		<view class="solid-bottom text-13 flex justify-between align-center padding bg-white">
			<view class="text-333 text-bold"> 配送地址 </view>
			<view class="flex justify-start align-center" @click="changeAddress(2)">
				<!-- <view class="text-767696 margin-right-xs">
					{{address2}}
				</view> -->
				<input type="text" v-model="address2" @input="getAddress2" disabled
					class="text-767696 margin-right-xs text-right" />
				<image :src="baseUrl + '/static/right.png'" mode="" style="width: 22rpx; height: 22rpx"></image>
			</view>
		</view>
		<view class="margin-bottom-sm bg-white text-13 flex justify-between align-center padding">
			<view class="text-333 flex-sub text-bold"> 详细地址 </view>
			<input type="text" value="" v-model="deliveryDetailedAddress" class="text-13 flex-treble"
				placeholder="详细地址，例1号楼1层1001室" />
		</view>
		<view class="solid-bottom text-13 flex justify-between align-center padding bg-white">
			<view class="text-333 text-bold"> 发货物品类型 </view>
			<view class="flex justify-start align-center" @click="changeAddress2">
				<view class="text-767696 margin-right-xs">
					{{ goodsTypeName }}
				</view>
				<image :src="baseUrl + '/static/right.png'" mode="" style="width: 22rpx; height: 22rpx"></image>
			</view>
		</view>
		<view class="solid-bottom bg-white text-13 flex justify-between align-center padding">
			<view class="text-333 flex-sub text-bold"> 物品重量(KG) </view>
			<input type="digit" v-model="weight" value="" @input="getWeight" class="text-13 flex-treble"
				placeholder="请填写物品重量" />
		</view>
		<view class="margin-bottom-sm bg-white text-13 flex justify-between align-center padding">
			<view class="flex justify-start align-center">
				<view class="text-bold text-333 margin-right"> 宽(cm) </view>
				<input type="digit" v-model="width" value="" class="text-13" style="width: 180rpx"
					placeholder="请填写物品宽度" />
			</view>
			<view class="flex justify-start align-center">
				<view class="text-bold text-333 margin-right"> 高(cm) </view>
				<input type="digit" v-model="height" value="" class="text-13" style="width: 180rpx"
					placeholder="请填写物品高度" />
			</view>
		</view>
		<view class="solid-bottom bg-white text-13 flex justify-between align-center padding">
			<view class="text-333 flex-sub text-bold"> 发货人 </view>
			<input type="text" value="" v-model="fromUserName" class="text-13 flex-treble" placeholder="请填写发货人姓名" />
		</view>
		<view class="margin-bottom-sm bg-white text-13 flex justify-between align-center padding">
			<view class="text-333 flex-sub text-bold"> 发货人电话 </view>
			<input type="number" value="" v-model="fromUserMobile" class="text-13 flex-treble" placeholder="请填写发货人电话" />
		</view>
		<view class="solid-bottom bg-white text-13 flex justify-between align-center padding">
			<view class="text-333 flex-sub text-bold"> 收货人 </view>
			<input type="text" value="" v-model="userName" class="text-13 flex-treble" placeholder="请填写收货人姓名" />
		</view>
		<view class="margin-bottom-sm bg-white text-13 flex justify-between align-center padding">
			<view class="text-333 flex-sub text-bold"> 收货人电话 </view>
			<input type="number" value="" v-model="mobile" class="text-13 flex-treble" placeholder="请填写收货人电话" />
		</view>
		<view class="bg-white solid-bottom text-13 flex justify-between align-center padding">
			<view class="text-333 flex-sub text-bold"> 详细描述 </view>
			<input type="text" v-model="desc" value="" class="text-13 flex-treble" placeholder="在这里描述下您的需求" />
		</view>
		<view class="cu-form-group padding-top">
			<view class="grid col-3 grid-square flex-sub">
				<view class="bg-img" v-for="(item, index) in picList" :key="index">
					<image :src="item" mode="aspectFill"></image>
					<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
						<text class="cuIcon-close"></text>
					</view>
				</view>
				<view class="solids" @tap="ChooseImage">
					<text class="cuIcon-cameraadd"></text>
				</view>
			</view>
		</view>
		<view v-if='!show' class="solid-bottom text-13 flex justify-between align-center padding">
			<view class="text-333 text-bold"> 支付方式 </view>
			<radio-group class="flex-treble flex justify-around align-center margin-left-xs" @change="RadioChange2">
				<view class="flex justify-start align-center">
					<radio class="radio yellow" :class="payType == 'A' ? 'bg-white' : ''"
						:checked="payType == 'A' ? true : false" value="A"></radio>
					<view class="title text-13 margin-left-xs">微信支付</view>
				</view>
				<view class="flex justify-start align-center">
					<radio class="radio yellow" :class="payType == 'B' ? 'checked' : ''"
						:checked="payType == 'B' ? true : false" value="B"></radio>
					<view class="title text-13 margin-left-xs">账户余额支付</view>
				</view>
			</radio-group>
		</view>
		<view class="flex justify-start align-center padding text-sm">
			<view class="flex justify-start align-center" @click="changeType">
				<image v-if="is_agree" :src="baseUrl + '/static/selected.png'" mode=""
					style="width: 26rpx; height: 26rpx"></image>
				<image v-else :src="baseUrl + '/static/unselected.png'" mode="" style="width: 26rpx; height: 26rpx">
				</image>
				<text class="text-333 margin-left-xs">同意并认真阅读</text>
			</view>
			<text class="color" @click="
          toPage(
            '/filePage/pages/protocol/protocol?title=佐佑帮信息发布协议&code=PROTOCOL_INFO_PUBLISH&type=4'
          )
        ">《佐佑帮信息发布协议》</text>
		</view>
		<view class="" style="padding: 58rpx 20rpx">
			<button @click="submit" class="bg-color text-15 padding radius10 text-center text-white">
				支付¥{{ parseFloat(price / 100).toFixed(2) }}
			</button>
		</view>

		<!-- <w-picker
		        :visible="visible"
		        mode="region"
		        value="['100','10010','1001010']"
		        default-type="value"
		        :hide-area="false"
		        @confirm="onConfirm($event)"
		        @cancel="changeAddress('')"
		        ref="region" 
		    ></w-picker> -->
		<w-picker :visible="visible2" mode="linkage" :value="[]" :options="options" :level="2" default-type="id"
			:default-props="defaultProps1" @confirm="onConfirm2($event)" @cancel="changeAddress2" ref="linkage">
		</w-picker>
		<passkeyborad :money='money' @message='message' @close='close' :show="show"></passkeyborad>
	</view>
	</view>
</template>

<script>
	import passkeyborad from '@/components/yzc-paykeyboard/yzc-paykeyboard.vue'
	export default {
		data() {
			return {
				baseUrl: this.$config.baseUrl,
				picList: [],
				addressType: "",
				mobile: "",
				addressCode: "",
				address: "请选择",
				deliveryAddressCode: "",
				address2: "请选择",
				detailedAddress: "",
				deliveryDetailedAddress: "",
				weight: "",
				width: "",
				height: "",
				desc: "",
				is_agree: false,
				// visible:false,
				visible2: false,
				defaultProps1: {
					label: "name",
					value: "id",
					children: "children",
				},
				options: [],
				goodsType: "",
				goodsTypeName: "请选择",
				userName: "",
				price: 0.0,
				addressLongitude: "",
				addressLatitude: "",
				deliveryLatitude: "",
				deliveryLongitude: "",
				payType: "A",
				fromUserMobile: "",
				fromUserName: "",
				show: false,
				password: 0,
				money: 0,
				serviceType: '',
				orderNo: ''
			};
		},
		components: {
			passkeyborad
		},
		onShow() {
			this.getTreeList();
		},
		methods: {
			getWeight(e) {
				if (this.addressLatitude && this.deliveryLongitude && e.detail.value) {
					this.getDeliveryCost();
				}
			},
			getAddress(e) {
				if (this.weight && this.deliveryLongitude && e.detail.value) {
					this.getDeliveryCost();
				}
			},
			getAddress2(e) {
				// console.log(e.detail.value)
				// addressLatitude:this.addressLatitude,
				// addressLongitude:this.addressLongitude,
				// deliveryLatitude:this.deliveryLatitude,
				// deliveryLongitude:this.deliveryLongitude,
				// weight:this.weight,
				if (this.addressLatitude && this.weight && e.detail.value) {
					this.getDeliveryCost();
				}
			},
			async ChooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ["album"], //从相册选择
					success: (res) => {
						// console.log(res)
						this.$upload(res.tempFilePaths[0]).catch((req) => {
							console.log(req);
							this.picList.push(req.data);
						});
					},
				});
			},
			DelImg(e) {
				uni.showModal({
					title: "提示",
					content: "确定要删除吗？",
					cancelText: "取消",
					confirmText: "确定",
					success: (res) => {
						if (res.confirm) {
							this.picList.splice(e.currentTarget.dataset.index, 1);
						}
					},
				});
			},
			toPage(url) {
				this.$util.openNewPage(url);
			},
			RadioChange2(e) {
				this.payType = e.detail.value;
			},
			changeAddress(e) {
				let that = this;
				// #ifdef  APP-PLUS
				uni.navigateTo({
					url: "/pagesA/pages/chooseLocation/chooseLocation?ship=1&index="+e,
					animationType: "slide-in-bottom",
				})
				// #endif
				// #ifdef  MP-WEIXIN
				uni.chooseLocation({
					success: function(res) {
						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);

						if (e == 1) {
							that.addressLatitude = res.latitude;
							that.addressLongitude = res.longitude;
							that.address = res.address;
							that.detailedAddress = res.name;
						} else {
							that.deliveryLatitude = res.latitude;
							that.deliveryLongitude = res.longitude;
							that.address2 = res.address;
							that.deliveryDetailedAddress = res.name;
						}
					},
				});
				// #endif
			},
			changeAddress2() {
				this.visible2 = !this.visible2;
			},
			// onConfirm(e){
			// 	this.changeAddress()
			// 	if(this.addressType==1){
			// 		this.addressCode = e.value
			// 	this.address = e.result
			// 	}else{
			// 		this.deliveryAddressCode = e.value
			// 		this.address2 = e.result
			// 	}

			// 	// console.log(e)
			// },
			async getTreeList() {
				const [err, res] = await this.$get(this.$api.home_categoryTreeList, {
					type: 1,
				});
				if (res) {
					this.options = res.data;
					console.log(res);
				}
			},
			onConfirm2(e) {
				this.changeAddress2();
				this.goodsType = e.value[1];
				this.goodsTypeName = e.obj.col2.name;

				// console.log(e)
			},
			async submit() {
				if (!this.is_agree) {
					this.$util.msg("未同意发布协议");
					return;
				}

				if (!this.addressLatitude && !this.addressLongitude) {
					return this.$util.msg("取货地址不能为空");
				}

				if (!this.detailedAddress) {
					return this.$util.msg("取货详细地址不能为空");
				}

				if (!this.deliveryLatitude && !this.deliveryLongitude) {
					return this.$util.msg("配送地址不能为空");
				}

				if (!this.deliveryDetailedAddress) {
					return this.$util.msg("配送详细地址不能为空");
				}

				if (!this.goodsType) {
					return this.$util.msg("物品类型不能为空");
				}

				if (!this.weight) {
					return this.$util.msg("重量不能为空");
				}

				if (!this.width) {
					return this.$util.msg("宽不能为空");
				}

				if (!this.height) {
					return this.$util.msg("高不能为空");
				}

				if (!this.fromUserName) {
					return this.$util.msg("发货人不能为空");
				}

				if (!this.fromUserMobile) {
					return this.$util.msg("发货人电话不能为空");
				}

				if (!this.userName) {
					return this.$util.msg("联系人不能为空");
				}

				if (!this.mobile) {
					return this.$util.msg("联系电话不能为空");
				}

				if (!this.desc) {
					return this.$util.msg("描述不能为空");
				}
				if (this.picList.length == 0) {
					return this.$util.msg("图片不能为空");
				}

				// if(!this.goodsType || !this.mobile|| !this.fromUserMobile || !this.fromUserName || !this.userName || !this.addressLatitude || !this.deliveryLatitude || !this.deliveryDetailedAddress || !this.desc || !this.detailedAddress || this.picList.length==0 || !this.height || !this.weight || !this.width){
				// 	this.$util.msg('请完善信息')
				// 	return
				// }
				uni.showLoading({
					title: "正在发货",
					mask: true,
				});
				const [err, res] = await this.$post(this.$api.home_addOrderDelivery, {
					goodsType: this.goodsType,
					mobile: this.mobile,
					serviceType: 2,
					userName: this.userName,
					addressLatitude: this.addressLatitude,
					addressLongitude: this.addressLongitude,
					deliveryLatitude: this.deliveryLatitude,
					deliveryLongitude: this.deliveryLongitude,
					deliveryDetailedAddress: this.deliveryDetailedAddress,
					desc: this.desc,
					detailedAddress: this.detailedAddress,
					height: this.height,
					picList: this.picList,
					weight: this.weight,
					width: this.width,
					price: this.price,
					fromUserMobile: this.fromUserMobile,
					fromUserName: this.fromUserName,
				});
				if (res) {
					// this.$util.msg(res.message)
					// setTimeout(() =>{
					// 	uni.navigateBack()
					// },1500)
					// console.log(res)
					this.orderNo = res.data.orderNo
					this.serviceType = res.data.serviceType

					// #ifdef  MP-WEIXIN
					const data = {
						orderNo: res.data.orderNo,
						orderType: res.data.serviceType,
						payWay: 1,
						appId: this.$config.wxAppId,
						openId: uni.getStorageSync('openid')
					};
					// #endif

					// #ifdef  APP-PLUS
					const data = {
						orderNo: res.data.orderNo,
						orderType: res.data.serviceType,
						payWay: 2,
						appId: this.$config.appId,
						openId: uni.getStorageSync('openid')
					};
					// #endif
					if (this.payType == "A") {
						const [error, rs] = await this.$get(this.$api.weixinPay, data);
						if (rs) {
							console.log(rs);
							const data = rs.data;
							uni.hideLoading();
							// #ifdef  MP-WEIXIN
							uni.requestPayment({
								provider: "wxpay",
								appId: data.appId,
								timeStamp: data.timeStamp,
								nonceStr: data.nonceStr,
								package: data._package,
								signType: data.signType,
								paySign: data.paySign,
								success: function(res) {
									console.log("success:" + JSON.stringify(res));

									setTimeout(() => {
										uni.navigateBack()
									}, 1500)
								},
								fail: function(err) {
									console.log("fail:" + JSON.stringify(err));
								},
							});
							// #endif

							// #ifdef  APP-PLUS
							uni.requestPayment({
								"provider": "wxpay",
								"orderInfo": {
									"appid": data.appId, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
									"noncestr": data.nonceStr, // 随机字符串
									"package": data._package, // 固定值
									"partnerid": data.partnerid, // 微信支付商户号
									"prepayid": data.prepayid, // 统一下单订单号 
									"timestamp": data.timeStamp, // 时间戳（单位：秒）
									"sign": data.sign // 签名，这里用的 MD5 签名
								},
								success(res) {
									setTimeout(() => {
										uni.navigateBack()
									}, 1500)
								},
								fail(e) {}
							})
							// #endif
						}
					} else {
						this.money = Number(this.price)
						console.log(this.price)
						console.log(this.money)
						this.show = true

						uni.hideLoading()





						// const [error, res] = await this.$get(
						//   this.$api.orderService_accountPay,
						//   data
						// );
						// if (res) {
						//   // console.log(res);
						//   this.$util.msg(res.message);
						//   uni.hideLoading();
						//   setTimeout(() => {
						//     uni.navigateBack();
						//   }, 1500);
						// }
					}
					// const [error, rs] = await this.$get(this.$api.weixinPay, data);
					// if (rs) {
					// 	console.log(rs);
					// 	uni.hideLoading();
					// 	const data = rs.data;
					// 	uni.requestPayment({
					// 		provider: "wxpay",
					// 		appId: data.appId,
					// 		timeStamp: data.timeStamp,
					// 		nonceStr: data.nonceStr,
					// 		package: data._package,
					// 		signType: data.signType,
					// 		paySign: data.paySign,
					// 		success: function(res) {

					// 			console.log("success:" + JSON.stringify(res));
					// 			// setTimeout(() => {
					// 			// 	uni.navigateBack()
					// 			// }, 1500)
					// 		},
					// 		fail: function(err) {
					// 			console.log("fail:" + JSON.stringify(err));
					// 		},
					// 	});
					// }
				}
			},
			changeType() {
				this.is_agree = !this.is_agree;
			},
			async getDeliveryCost(e) {
				// if(!this.is_agree){
				// 	this.$util.msg('未同意发布协议')
				// 	return
				// }
				// if(!this.addressLatitude || !this.deliveryLatitude || !this.addressLongitude || !this.deliveryLongitude || !this.weight){
				// 	this.$util.msg('请完善信息')
				// 	return
				// }
				const [err, res] = await this.$get(
					this.$api.orderService_computeDeliveryCost, {
						addressLatitude: this.addressLatitude,
						addressLongitude: this.addressLongitude,
						deliveryLatitude: this.deliveryLatitude,
						deliveryLongitude: this.deliveryLongitude,
						weight: this.weight,
					}
				);
				if (res) {
					this.price = res.data;

					// console.log(res)
					// uni.showModal({
					// 	title: '提示',
					// 	content: '支付金额' + this.price + '，确定要发货吗？',
					// 	cancelText: '取消',
					// 	confirmText: '确定',
					// 	success: res => {
					// 		if (res.confirm) {
					// 			this.submit()
					// 		}
					// 	}
					// })
				}
			},
			close() {
				console.log(111111)
				this.show = false
			},
			message(password) {
				console.log(password)
				var CusBase64 = require('@/common/js/base64.js');
				//函数调用
				var passWord = CusBase64.CusBASE64.encoder(password);
				this.$get(this.$api.verifyPayPassWord, {
					passWord,
					userId: uni.getStorageSync('userId')
				}).then(res => {
					const [err, rs] = res
					if (rs) {
						const data = {
							orderNo: this.orderNo,
							orderType: this.serviceType
						};
						this.$get(this.$api.orderService_accountPay, data).then(result => {
							const [err, rs] = result
							if (rs) {
								this.$util.msg(rs.message)
								this.show = false
								setTimeout(() => {
									uni.navigateBack()
								}, 1500)
							}
						})

					}
					if (err) {
						this.show = false
						if (err.message == '请去设置密码！') {
							setTimeout(() => {
								uni.navigateTo({
									url: '/pagesA/pages/setPassword/setPassword'
								})
							}, 1500)
						}
					}
				})

			},
		},
	};
</script>

<style lang="scss" scoped>
	radio.radio[checked]::after,
	radio.radio .uni-radio-input-checked::after {
		z-index: 1;
	}
</style>
